package com.red.wood.common.util;

import java.security.Key;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenUtils {

	private static final Log log = LogFactory.getLog(TokenUtils.class);
	
	/**
	 * 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
	 * @param claims
	 * @return
	 */
	public static String createJavaWebToken(Map<String, Object> claims) {
		String token = "";
		try {
			token =  Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return token;
	}
	
	/**
	 * 解析Token，同时也能验证Token，当验证失败返回null
	 * @param jwt
	 * @return
	 */
	public static Map<String, Object> parserJavaWebToken(String jwt) {
		Map<String, Object> jwtClaims = null;
		try {
			jwtClaims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return jwtClaims;
	}
	
	public static Key getKeyInstance() {
		// We will sign our JavaWebToken with our ApiKey secret
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("api_service");
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		return signingKey;
	}
}
